import {createRouter, createWebHistory} from "vue-router";
import {routerList} from "@/router/router.ts";
import {otherRouter} from "@/router/other.ts";
import {useUserStore} from "@/store/user.ts";

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        ...routerList,
        ...otherRouter
    ],
    // 切换路由跳转到顶部
    scrollBehavior() {
        return {
            left: 0,
            top: 0
        }
    }
})

// 全局前置守卫
router.beforeEach((to, _, next) => {
    document.title = to.meta.title as string
    const userStore = useUserStore()
    const token = userStore.adminToken
    if (to.path !== '/login') {
        if (!token) {
            next({path: '/login'})
        } else {
            next()
        }
    } else {
        next()
    }
})

export default router